//登录与注册的模块
import {reqGetCode, reqUserLogin, reqUserRegister} from "../network/home";
import {reqUserInfo, reqLogout} from "../network/home";
import {setToken, getToken, removeToken} from "../utils/token";

const state = {
  code: '',
  token: getToken(),
  userInfo: {}
};
const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state, token) {
    state.token = token
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  CLEAR(state) {
    //把仓库中相关用户信息清空
    state.token = '';
    state.userInfo = {};
    //本地存储数据清空
    removeToken()

  }
};
const actions = {
  //获取验证码
  async getCode({commit}, phone) {
    let result = await reqGetCode(phone)
    console.log(result)
    if (result.code === 200) {
      commit('GETCODE', result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }

  },

  //用户注册
  // eslint-disable-next-line no-unused-vars
  async userRegister({commit}, user) {
    let result = await reqUserRegister(user)
    // console.log(result)
    if (result.code === 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },

  //登录业务
  async userLogin({commit}, data) {
    let result = await reqUserLogin(data);
    // console.log(result)
    //服务器下发的token, 用户唯一标识
    if (result.code === 200) {
      //用户已经登录成功，且获取到token
      commit('USERLOGIN', result.data.token)
      //持久化存储token
      // localStorage.setItem('token', result.data.token)
      setToken(result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },

  //获取用户信息
  async getUserInfo({commit}) {
    let result = await reqUserInfo()
    // console.log(result)
    if (result.code === 200) {
      commit('GETUSERINFO', result.data)
      return 'ok'
    } else {
      console.log('未登录')
      // return Promise.reject(new Error('faile'))
    }
  },

  //退出登录
  async userLogout({commit}) {
    //向服务器发起一次请求
    let result = await reqLogout()
    if (result.code === 200) {
      commit('CLEAR');
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  }
};
const getters = {};

export default {
  state,
  actions,
  mutations,
  getters
}